package com.btg.set.http;

import com.alibaba.fastjson.JSONObject;
import com.btg.set.util.Utils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.*;

/**
 * Created by Administrator on 2016/12/1.
 */
public class ResourceServlet extends HttpServlet {
    protected final String resourcePath;

    public ResourceServlet(String resourcePath) {
        this.resourcePath = resourcePath;
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String contextPath = req.getContextPath();
        String servletPath = req.getServletPath();
        String requestURI = req.getRequestURI();

        resp.setCharacterEncoding("utf-8");

        if (contextPath == null) { // root context
            contextPath = "";
        }
        String uri = contextPath + servletPath;
        String path = requestURI.substring(contextPath.length() + servletPath.length());

        if ("".equals(path)) {
            if (contextPath.equals("") || contextPath.equals("/")) {
                resp.sendRedirect("/btgset/index.html");
            } else {
                resp.sendRedirect("btgset/index.html");
            }
            return;
        }

        if ("/".equals(path)) {
            resp.sendRedirect("index.html");
            return;
        }
        if (path.contains(".json")) {
            String fullUrl = path;
            if (req.getQueryString() != null && req.getQueryString().length() > 0) {
                fullUrl += "?" + req.getQueryString();
            }
            resp.getWriter().print(process(fullUrl, getParas(req)));
            return;
        }
        returnResourceFile(path, uri, resp);
    }

    protected String getFilePath(String fileName) {
        return resourcePath + fileName;
    }

    protected void returnResourceFile(String fileName, String uri, HttpServletResponse response)
            throws ServletException,
            IOException {

        String filePath = getFilePath(fileName);

        if (filePath.endsWith(".html")) {
            response.setContentType("text/html; charset=utf-8");
        }
        if (fileName.endsWith(".jpg") || fileName.endsWith(".png") || fileName.endsWith(".gif")) {
            byte[] bytes = Utils.readByteArrayFromResource(filePath);
            if (bytes != null) {
                response.getOutputStream().write(bytes);
            }

            return;
        }

        String text = Utils.readFromResource(filePath);
        if (text == null) {
            response.sendRedirect(uri + "/index.html");
            return;
        }
        if (fileName.endsWith(".css")) {
            response.setContentType("text/css;charset=utf-8");
        } else if (fileName.endsWith(".js")) {
            response.setContentType("text/javascript;charset=utf-8");
        }
        response.getWriter().write(text);
    }

    private JSONObject getParas(HttpServletRequest req) {
        JSONObject object = new JSONObject();

        // 获取request参数
        Enumeration en = req.getParameterNames();
        while (en.hasMoreElements()) {
            String paramName = (String) en.nextElement();
            String paramValue = req.getParameter(paramName);
            object.put(paramName, paramValue);
        }
        return object;
    }

    private Object process(String url, JSONObject params) {

        String methodName = url.substring(url.lastIndexOf("/") + 1, url.indexOf("."));
        try {
            // 利用反射获取方法
            Method method = getClass().getDeclaredMethod(methodName, JSONObject.class);
            // 执行相应的方法
            return method.invoke(this, params);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new JSONObject();
    }


}
